package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.JwtUtils;
import com.leyou.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * lcd  2020/6/15
 * Description:
 */

@Service
public class AuthService {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserClient userClient;

    public String accredit(String username, String password) {
        User user = userClient.queryUser(username, password);
        if (user == null) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        try {
            return JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),jwtProperties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new LyException(ExceptionEnum.UNAUTHORIZED);
    }
}
